package com.nbsaas.boot.otp.utils;

import org.apache.commons.codec.binary.Base32;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.time.Instant;
import java.util.stream.IntStream;

public class TOTPUtil {

    private static final String HMAC_ALGORITHM = "HmacSHA1";
    public static final int TIME_STEP_SECONDS = 30; // 时间窗口
    private static final int OTP_LENGTH = 6; // OTP 长度
    private static final int VALIDATION_WINDOW = 2; // 允许的时间窗口偏移（前后各一个时间窗口）

    // 生成 TOTP 动态码
    public static String generateTOTP(String secretKey) throws Exception {
        return generateTOTP(secretKey, getCurrentTimeIndex());
    }

    public static String generateSecretKey() {
        byte[] buffer = new byte[10];
        new java.security.SecureRandom().nextBytes(buffer);
        return new Base32().encodeToString(buffer).replace("=", "");
    }
    // 验证 TOTP 动态码
    public static boolean validateTOTP(String secretKey, String inputOTP) throws Exception {
        long currentIndex = getCurrentTimeIndex();

        // 检查当前窗口及其前后几个时间窗口的 OTP 是否匹配
        return IntStream.rangeClosed(-VALIDATION_WINDOW, VALIDATION_WINDOW)
                .mapToObj(offset -> {
                    try {
                        System.out.println("offset:" + offset);
                        String key=generateTOTP(secretKey, currentIndex + offset);
                        System.out.println("key:" + key);
                        return key;
                    } catch (Exception e) {
                        return null;
                    }
                })
                .anyMatch(inputOTP::equals);
    }

    // 生成指定时间窗口的 TOTP
    private static String generateTOTP(String secretKey, long timeIndex) throws Exception {
        Base32 base32 = new Base32();
        byte[] keyBytes = base32.decode(secretKey);

        // 转换时间为字节数组
        byte[] data = new byte[8];
        for (int i = 7; i >= 0; i--) {
            data[i] = (byte) (timeIndex & 0xFF);
            timeIndex >>= 8;
        }

        // 使用 HMAC-SHA1 算法生成哈希值
        Mac mac = Mac.getInstance(HMAC_ALGORITHM);
        mac.init(new SecretKeySpec(keyBytes, HMAC_ALGORITHM));
        byte[] hash = mac.doFinal(data);

        // 截取动态部分
        int offset = hash[hash.length - 1] & 0xF;
        int binary = ((hash[offset] & 0x7F) << 24) |
                     ((hash[offset + 1] & 0xFF) << 16) |
                     ((hash[offset + 2] & 0xFF) << 8) |
                     (hash[offset + 3] & 0xFF);

        // 转换为 OTP
        return String.format("%0" + OTP_LENGTH + "d", binary % (int) Math.pow(10, OTP_LENGTH));
    }

    // 获取当前时间的时间窗口索引
    private static long getCurrentTimeIndex() {
        return Instant.now().getEpochSecond() / TIME_STEP_SECONDS;
    }
}
